<template>
  <a-modal
    title-align="start"
    v-model:visible="visible"
    @close="handleCancel(formRef)"
  >
    <template #title>{{ curId ? '编辑' : '创建' }}</template>
    <a-form ref="formRef" :model="formData">
      <a-form-item
        field="name"
        label="角色"
        label-col-flex="40px"
        :rules="[{ required: true, message: 'name is required' }]"
        :validate-trigger="['change', 'input']"
      >
        <a-input v-model="formData.name" placeholder="请输入角色" />
      </a-form-item>
      <a-form-item
        field="code"
        label="编码"
        label-col-flex="40px"
        :rules="[{ required: true, message: 'code is required' }]"
        :validate-trigger="['change', 'input']"
      >
        <a-input v-model="formData.code" placeholder="请输入角色编码" />
      </a-form-item>
      <a-form-item
        field="sort"
        label="排序"
        label-col-flex="40px"
        :rules="[{ required: true, message: 'sort is required' }]"
        :validate-trigger="['change', 'input']"
      >
        <a-input v-model="formData.sort" placeholder="请输入排序" />
      </a-form-item>
      <a-form-item
        field="status"
        label="状态"
        label-col-flex="40px"
        :rules="[{ required: true, message: 'status is required' }]"
        :validate-trigger="['change', 'input']"
      >
        <a-switch v-model="formData.status" type="round">
          <template #checked> ON </template>
          <template #unchecked> OFF </template>
        </a-switch>
      </a-form-item>
      <a-form-item field="description" label="描述" label-col-flex="40px">
        <a-textarea
          placeholder="描述内容"
          v-model="formData.description"
          allow-clear
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="visible = false">取消</a-button>
      <a-button type="primary" @click="handleOk">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { login } from '@/api/user';
import { ref, defineEmits, reactive } from 'vue';
const formRef = ref<any>(null);
const formData = reactive<any>({
  id: '',
  name: '',
  sort: '',
  status: false,
  code: '',
  description: '',
});
const visible = ref(false);
const curId = ref('');
const handleClick = (val: any) => {
  visible.value = true;
  if (val && val.id) {
    curId.value = val.id;
    Object.keys(val).forEach((item: string) => {
      formData[item] = val[item];
    });
  }
};
const emits = defineEmits(['submitFrom']);
const handleOk = async () => {
  const res = await formRef.value?.validate();
  if (!res) {
    emits('submitFrom', formData, curId.value);
  }
};
const handleCancel = (formEl: any) => {
  curId.value = '';
  formEl.resetFields();
};
defineExpose({ handleClick, visible });
</script>

<style scoped lang="less">
.title_style {
  color: #ff7d00;
}
</style>
